﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using NGourd.Core.Steps;
using System.IO;
using NGourd.Core.Parser;

namespace NGourd.Core.Runners
{
    class Librarian
    {
        private readonly FeatureLibrary features;
        private readonly StepLibrary steps;

        public Librarian(FeatureLibrary features, StepLibrary steps)
        {
            this.features = features;
            this.steps = steps;
        }

        public void AddAssemblyToLibraries(Assembly assembly)
        {
            var types = assembly.GetTypes();

            foreach (var type in types)
            {
                if (type.IsAbstract || type.IsInterface || type.IsEnum)
                    continue;

                if (typeof(NGourd.Core.Features.Feature).IsAssignableFrom(type))
                    features.AddFeatureType(type);

                if (type.GetCustomAttributes(typeof(StepsAttribute), true).Length > 0)
                    steps.AddSteps(Activator.CreateInstance(type));
            }

            var resourceNames = assembly.GetManifestResourceNames();
            var featureFileNames = resourceNames.Where(r => r.EndsWith(".feature", StringComparison.InvariantCultureIgnoreCase));
            foreach (var featureFileName in featureFileNames)
            {
                using (var stream = assembly.GetManifestResourceStream(featureFileName))
                using (var streamReader = new StreamReader(stream))
                {
                    var feature = FeatureParser.Parse(streamReader);
                    features.AddFeature(feature);
                }
            }
        }

        public void AddFeatureFileToLibrary(FileInfo file)
        {
            if (file.Exists)
            {
                var feature = FeatureParser.Parse(file);
                features.AddFeature(feature);
            }
        }
    }
}
